import * as React from "react";
import { Button, Modal, Spin, Table, Input } from "antd";
import { SearchOutlined } from "@ant-design/icons";
import {
  AjaxData,
  columnsDataCLass,
} from "../../../../../../data/interface/publicInterface";
import {
  getUnBoundDevices,
  getBoundDevices,
  configDevice,
} from "../../../ServeApi/index";
import { ergodicListAddIdToKey } from "../../../../../../utils/common";

export interface FeedModelBindProps {
  isFeedModalVisible: boolean;
  record: any | null;
  onCancel: () => any;
}

export interface FeedModelBindState {
  feedloading: boolean;
  selectedRowKeys: any[];
}

class FeedModelBind extends React.Component<
  FeedModelBindProps,
  FeedModelBindState
> {
  private pageIndex: number = 1;
  private pageSize: number = 10;
  private total: number = 0;
  private dataSouce: any[] = [];
  private likeStr = "";
  bound: number = 1;
  private columns2: columnsDataCLass[] = [
    {
      title: "设备名称",
      dataIndex: "deviceName",
      key: "deviceName",
    },
    {
      title: "设备地址",
      dataIndex: "deviceAddress",
      key: "deviceAddress",
    },
    {
      title: "安装地址",
      dataIndex: "terminalAddress",
      key: "terminalAddress",
    },
  ];

  state = { feedloading: false, selectedRowKeys: [] };
  render() {
    let { isFeedModalVisible } = this.props;
    let { bound } = this;
    const { selectedRowKeys } = this.state;
    const rowSelection = {
      selectedRowKeys,
      onChange: this.onSelectChange,
    };
    return (
      <>
        <Modal
          title="绑定设备"
          visible={isFeedModalVisible}
          okText="添加"
          okType="ghost"
          onCancel={() => {
            // this.handleFeedCancel();
            this.props.onCancel();
          }}
          footer={[
            <Button
              key="back"
              onClick={() => {
                this.props.onCancel();
              }}
            >
              关闭
            </Button>,
          ]}
        >
          <div className="bare_body">
            <div className="changeType_btn d_inlineFlex">
              <Button
                className="left"
                type={bound === 1 ? "primary" : "default"}
                onClick={() => {
                  this.changeBound(1);
                  this.forceUpdate();
                }}
              >
                已绑
              </Button>
              <Button
                className="right"
                type={bound === 2 ? "primary" : "default"}
                onClick={() => {
                  this.changeBound(2);
                  this.forceUpdate();
                }}
              >
                未绑
              </Button>
            </div>
            <div className="f-right" style={{ textAlign: "right" }}>
              <Input.Group compact>
                <Input
                  style={{ width: "60%" }}
                  placeholder="关键字搜索"
                  bordered={false}
                  onChange={(e) => {
                    this.likeStr = e.target.value;
                    this.forceUpdate();
                  }}
                  value={this.likeStr}
                  prefix={
                    <SearchOutlined
                      onClick={() => {
                        this.onSeach();
                      }}
                    />
                  }
                />
                {bound === 1 ? (
                  <Button
                    type="primary"
                    onClick={() => {
                      this.setBindPream();
                    }}
                    style={{
                      background: "#F4990D",
                      borderColor: "#F4990D",
                    }}
                  >
                    解绑
                  </Button>
                ) : (
                  <Button
                    type="primary"
                    onClick={() => {
                      this.setBindPream();
                    }}
                  >
                    绑定
                  </Button>
                )}
              </Input.Group>
            </div>
          </div>
          <Spin spinning={this.state.feedloading}>
            <Table
              style={{ marginTop: 10 }}
              columns={this.columns2}
              dataSource={this.dataSouce}
              rowSelection={rowSelection}
              pagination={{
                pageSize: this.pageSize,
                total: this.total,
                current: this.pageIndex,
                onChange: (page: number) => {
                  this.pageIndex = page;
                  this.serPream();
                },
              }}
            />
          </Spin>
        </Modal>
      </>
    );
  }
  componentDidMount() {
    this.init();
  }
  init() {
    this.serPream();
  }

  /** 主动操作*/
  //搜索
  onSeach() {
    this.pageIndex = 1;
    this.serPream();
  }
  //选中的设备
  onSelectChange = (selectedRowKeys) => {
    this.setState({ selectedRowKeys });
  };
  //绑定，未绑定切换
  changeBound(bound: number) {
    this.bound = bound;
    this.likeStr = "";
    this.serPream();
    this.forceUpdate();
  }
  /**函数方法 */
  clearState() {
    this.setState({ selectedRowKeys: [] });
  }
  //绑定，解绑
  setBindPream() {
    let pream: any = null;
    switch (this.bound) {
      case 1: //解绑
        pream = {
          amiId: this.props.record["id"],
          bound: false,
          ids: this.state.selectedRowKeys,
        };
        this.configDevice(pream);
        break;
      case 2: //绑定
        pream = {
          amiId: this.props.record["id"],
          bound: true,
          ids: this.state.selectedRowKeys,
        };
        this.configDevice(pream);
        break;
      default:
        break;
    }
  }
  //设备列表参数与数据调用
  serPream() {
    let { record } = this.props;
    let pream: any = {};
    if (record) {
      pream = {
        amiId: record.id,
        protocalTypeId: record.protocalTypeId,
        pageIndex: this.pageIndex,
        pageSize: this.pageSize,
        likeStr: this.likeStr,
      };
      this.clearState();
      switch (this.bound) {
        case 1: //已绑
          this.getBoundDevices(pream);
          break;
        case 2: //未绑
          this.getUnBoundDevices(pream);
          break;
        default:
          break;
      }
    }
  }
  /**数据请求 */
  //采集方案已绑定的设备分页查询;
  async getBoundDevices(item) {
    let _this = this;
    this.setState({ feedloading: true });
    try {
      let res: any = await getBoundDevices(JSON.stringify(item)).catch(
        (err) => {
          console.log(err);
        }
      );
      let json: AjaxData = res;
      if (json.success) {
        _this.setState({ feedloading: false });
        _this.dataSouce = ergodicListAddIdToKey(json.data.records);

        _this.total = json.data.total;
        _this.forceUpdate();
      } else {
        Modal.error({
          title: json.message,
          onOk: () => {
            _this.setState({ feedloading: false });
          },
        });
      }
    } catch (error) {
      Modal.error({
        title: "初始化程序失败，无法读取数据，请刷新页面。",
        onOk: () => {
          _this.setState({ feedloading: false });
        },
      });
      console.error(error);
    }
  }
  //采集方案未绑定的设备分页查询;
  async getUnBoundDevices(item) {
    let _this = this;
    this.setState({ feedloading: true });
    try {
      let res: any = await getUnBoundDevices(JSON.stringify(item)).catch(
        (err) => {
          console.log(err);
        }
      );
      let json: AjaxData = res;
      if (json.success) {
        _this.setState({ feedloading: false });
        _this.dataSouce = ergodicListAddIdToKey(json.data.records);
        _this.total = json.data.total;
        _this.forceUpdate();
      } else {
        Modal.error({
          title: json.message,
          onOk: () => {
            _this.setState({ feedloading: false });
          },
        });
      }
    } catch (error) {
      Modal.error({
        title: "初始化程序失败，无法读取数据，请刷新页面。",
        onOk: () => {
          _this.setState({ feedloading: false });
        },
      });
      console.error(error);
    }
  }
  //采集方案未绑定的设备分页查询;
  async configDevice(item) {
    let _this = this;
    this.setState({ feedloading: true });
    try {
      let res: any = await configDevice(JSON.stringify(item)).catch((err) => {
        console.log(err);
      });
      let json: AjaxData = res;
      if (json.success) {
        _this.setState({ feedloading: false });
        _this.pageIndex = 1;
        _this.serPream();
        _this.forceUpdate();
      } else {
        Modal.error({
          title: json.message,
          onOk: () => {
            _this.setState({ feedloading: false });
          },
        });
      }
    } catch (error) {
      Modal.error({
        title: "初始化程序失败，无法读取数据，请刷新页面。",
        onOk: () => {
          _this.setState({ feedloading: false });
        },
      });
      console.error(error);
    }
  }
}

export default FeedModelBind;
